<template>
  <div class="w100 h100" v-loading="loading">
    <ul class="w100 h100 alarm-scroll" v-if="hasAlarm" id="alarmScroll">
      <li class="alarm" v-for="(item, index) in alarmList" :key="index" @click="viewDetails(item)" @mouseover="stopMove" @mouseout="startMove">
        <img class="speaker" src="../../static/image/common/speaker.png" alt="">
        {{getAddress(item)}} 于 {{getAlarmDate(item)}} 发出 {{getAlarmType(item)}}{{getDeviceType(item)}} 请尽快处理
      </li>
    </ul>
  </div>
</template>

<script>
  // import { regionData } from 'element-china-area-data'
  import { regionData } from 'static/js/regionData'
  import { mapGetters } from 'vuex'
  import Config from '../config'
  export default {
    name: 'AlarmScroll',
    data () {
      return {
        alarmList: [],
        moveInterval: null, // 滚动计时器
        refreshInterval: null, // 刷新计时器
        MOVE_DIS: -30,
        index: 0,
        SCROLL_TIME: 5000,
        hasAlarm: false,
        loading: true
      }
    },
    computed: {
      ...mapGetters('user', {
        district: 'getDistrict',
        role: 'getRole'
      })
    },
    mounted () {
      this.getLatestAlarm();
      this.refreshInterval = setInterval(() => {
        this.getLatestAlarm()
      }, this.SCROLL_TIME * 50) // 基本5分钟请求一次数据
    },
    destroyed () {
      this.stopMove()
    },
    methods: {
      /**
       * 获取展示的地址
       * @param {JSON} item
       * */
      getAddress (item) {
        try {
          const province = this.getAreaObjByValue(regionData, item.province)
          const city = this.getAreaObjByValue(province.children, item.city)
          const district = this.getAreaObjByValue(city.children, item.district)

          return `${province.label}${city.label}${district.label}${item.siteAddress}`
        } catch (e) {
          return  ''
        }

      },
      /**
       * 获取展示的报警时间
       * @param {JSON} item
       * */
      getAlarmDate (item) {
        const date = new Date(item.ts)
        const year_month_date = `${this.$util.Date.getYear(date)}年${this.$util.Date.getMonth(date)}月${this.$util.Date.getDate(date)}日`
        const hour_minute_second = `${this.$util.Date.getHours(date)}时${this.$util.Date.getMinutes(date)}分${this.$util.Date.getMinutes(date)}秒`

        return `${year_month_date} ${hour_minute_second}`
      },
      /**
       * 获取展示的报警类型
       * @param {JSON} item
       * @return {String}
       * */
      getAlarmType (item) {
        return this.$util.Alarm.getNameByType(item.type)
      },
      /**
       * 获取设备类型
       * @param {JSON} item
       * @return {String}
       * */
      getDeviceType (item) {
        return `（${this.$util.Device.getDeviceTypeName(item.devname)}）`
      },
      /**
       * 获取区域信息
       * @param {Array} arr
       * @param {Array} value
       * @return {Object} obj
       * */
      getAreaObjByValue (arr, value) {
        let obj = null
        arr.some(item => {
          if (value === item.value) {
            obj = item
            return true
          }
        })
        return obj
      },
      /**
       * 获取最新的1报警
       * */
      getLatestAlarm () {
        const SIZE = 10 // 条数
        const url = `${Config.FIREPLUG_APP_URL}/fireplug/alarm/search?page=0&size=${SIZE}`;
        let param = {
          latest: true,
          sort: 'ts desc'
        };
        param = this.preHandleParam(param)

        if (this.role[0].sort === 93) {
          param.site_type = 'test'
        }else if (this.role[0].sort !== 100) {
          param.site_type = 'official'
        }
        // console.log('param ', param)
        this.$http.post(url, param)
          .then(data => {
            this.alarmList.splice(0)
            this.alarmList = data.content
            // console.log('data ', data)
            this.loading = false
            if (this.alarmList.length === 0) {
              return
            }
            this.hasAlarm = true
            this.$nextTick(() => this.startMove())
          })
          .catch(e => this.loading = false);
      },
      /**
       * 预处理查询参数
       * @param {JSON} param
       * */
      preHandleParam (param) {
        const province = this.district.provinceCode || ''
        const city = this.district.cityCode || ''
        const district = this.district.areaCode || ''
        const site_id = this.district.districtId || ''
        if (district) { // 包含区编码,角色为场所管理员
          if (site_id) {
            param = {...param, ...{site_id}}
          }
        } else {
          if (city) { // 包含市编码
            param = {...param, ...{city}}
          } else {
            if (province) { // 包含省编码
              param = {...param, ...{province}}
            }
          }
        }
        return param
      },
      /**
       * 开始滚动
       * */
      startMove () {
        this.moveInterval = setInterval(() => {
          this.changeTop()
        }, this.SCROLL_TIME)
      },
      changeTop () {
        const ul = document.getElementById('alarmScroll')
        if (!ul) {
          this.moveInterval && this.stopMove()
          return
        }
        const index = this.alarmList.length - 1
        // console.log(ul.style.top)
        if (ul.style.top === this.MOVE_DIS * index + 'px') {
          ul.style.top = '0px'
          this.index = 0
          clearInterval(this.moveInterval)
          this.startMove()
          return
        }
        this.index ++
        ul.style.top = this.MOVE_DIS * this.index + 'px'
      },
      /**
       * 暂停滚动
       * */
      stopMove () {
        clearInterval(this.moveInterval)
        this.moveInterval = null
        clearInterval(this.refreshInterval)
        this.refreshInterval = null
      },
      /**
       * 查看详情
       * */
      viewDetails (item) {
        if (item.subtype === 'individual') {
          this.$router.push({
            name: 'promptC',
            params: {
              id: item
            }
          })
        } else {
          this.$router.push({
            name: 'prompt',
            params: {
              id: item
            }
          })
        }
      }
    }
  }
</script>

<style lang="scss" scoped>
  .alarm-scroll {
    box-sizing: border-box;
    background-color: #FFF3C5;
    position: relative;
    top: 0px;
    transition: all 800ms;
    .alarm {
      width: 100%;
      padding-left: 24px;
      height: 30px;
      display: flex;
      align-items: center;
      background-color: #FFF3C5;
      font-size: 12px;
      color: #666;
      cursor: pointer;

      .speaker {
        width: 25px;
        height: 15px;
        margin-right: 8px;
      }
      /*animation: myMove 2s linear infinite;*/
    }
  }
</style>
